/* beautify ignore:start */
import {Directive, ElementRef, Renderer, EventEmitter,
    ContentChild, ContentChildren, QueryList, SimpleChange, ChangeDetectorRef, Input} from '@angular/core';
import {PaginationComponent} from '../components/pagination/pagination.component';
import {TableSort} from './table-sort.directive';
import {TableSearch} from './table-search.directive';
import {isPresent, isArray, isBlank} from '../../common';
/* beautify ignore:end */

@Directive({
    selector: '[wm-table]',
    inputs: ['rows: wm-table', '_src: safe'],
    outputs: ['tableChanged']
})
export class Table {
    private _inited: boolean = false;
    private rows: Array<any>;    // 用于分页/过滤/排序后 显示的集合
    private _src: Array<any>;     //
    public tableChanged: EventEmitter<any> = new EventEmitter();
    @ContentChild(PaginationComponent, {}) pagination: PaginationComponent; // 分页组件
    @ContentChildren(TableSort, {}) sorts: QueryList<TableSort>;
    @ContentChildren(TableSearch, {}) searchs: QueryList<TableSearch>;

    private _page: number = 1;  // 当前页数
    private _itemsPrePage: number; // 每页行数

    private _sortsField: any = {};
    private _searchField: any;
    private _searchAllField: string;

    constructor(private cdr: ChangeDetectorRef) {
    }

    ngOnInit() {
        this._inited = true;
    }

    ngAfterContentInit() {
        // 排序设置
        this.childInit();
    }

    childInit() {
        // 排序
        if (isPresent(this.sorts)) {
            this.sorts.forEach(this.setSort.bind(this)); // 绑定this
        }

        // 过滤设置
        if (isPresent(this.searchs)) {
            this.searchs.forEach(this.setSearch.bind(this)); // 绑定this
        }

        // 分页
        if (isPresent(this.pagination)) {
            // 跳转页面触发时
            this.pagination.pageChanged.subscribe((e: any) => {
                this._page = e.page;
                this._itemsPrePage = e.itemsPerPage;
                this._pipe();
            });

            this._itemsPrePage = this.pagination.itemsPerPage;
            this._pipe();
        }
    }

    ngOnChanges(changes: { [propName: string]: SimpleChange }) {
        if (changes['_src']) {
            this._pipe();
        }
    }

    // 设置查询
    private setSearch(search: TableSearch) {
        search.searchChanged.subscribe((e: any) => {
            if (isBlank(e.field)) {
                this._searchAllField = e.search;
            } else {
                if (isBlank(this._searchField)) {
                    this._searchField = {};
                }

                this._searchField[e.field] = e.search;
            }
            this._pipe();
        });
    }

    // 设置排序
    private setSort(sort: TableSort) {
        sort.sortChanged.subscribe((e:any) => {
            this._sortsField = e;
            this._pipe();
            // 设置只有一个排序
            this.sorts.forEach(function (f: TableSort) {
                if (e.field !== f.field) {
                    f.removeClass();
                }
            });
        });
    }

    private _searchKeys(keys: string, item: any) {
        let keyArr = keys.split(',');
        let result = false;
        for (let key of keyArr) {
            if (String(item[key]).indexOf(this._searchField[keys]) !== -1) {
                result = true;
                break;
            }
        }
        return result;
    }

    private _pipe() {
        let filtered = [].concat(this._src);
        if (filtered && this.rows) {
            this.rows.splice(0, this.rows.length);
            // filter search 查询/过滤
            if (isPresent(this._searchAllField)) {
                let row = filtered[0];
                filtered = filtered.filter((item: any) => {
                    for (let key of Object.keys(row)) {
                        if (String(item[key]).indexOf(this._searchAllField) !== -1) {
                            return true;
                        }
                    }
                });
            }

            if (isPresent(this._searchField)) {
                filtered = filtered.filter((item: any) => {
                    let size = Object.keys(this._searchField).length;
                    for (let key of Object.keys(this._searchField)) {
                        let v = this._searchField[key];
                        if (v === '' || this._searchKeys(key, item)) {
                            size--;
                        }
                    }
                    return size === 0;
                });
            }

            // order by 排序
            if (isPresent(this.sorts)) {
                let field = this._sortsField.field;
                let sort = this._sortsField.sort;
                if (sort !== '') {
                    filtered.sort((previous: any, current: any) => {
                        if (sort === 'desc') {
                            return previous[field] > current[field] ? -1 : 1;
                        }
                        if (sort === 'asc') {
                            return previous[field] < current[field] ? -1 : 1;
                        }
                        return 0;
                    });
                }
            }

            // 分页
            if (isPresent(this.pagination)) {
                this.pagination.totalItems = filtered.length;
                this._itemsPrePage = this.pagination.itemsPerPage;

                // pagination 分页
                let start: number = (this._page - 1) * this._itemsPrePage;
                let end: number = start + this._itemsPrePage;
                end = end > filtered.length ? filtered.length : end;

                this.deepCopy(filtered, this.rows, start, end);
                this.cdr.detectChanges();
            } else {
                this.deepCopy(filtered, this.rows, 0, filtered.length);
            }
        }

        //this.tableChanged.emit();
    }

    // 深拷贝
    private deepCopy(src: any[], desc: any[], start: number, end: number) {
        src.slice(start, end).forEach(function (i) {
            desc.push(i);
        });
    }
}